package entity

import (
	"gitee.com/night-tc/gobige/common"
	"gitee.com/night-tc/gobige/global"
	"gitee.com/night-tc/gobige/logger"
	"gitee.com/night-tc/gobige/msgdef/protomsg"
)

type EntitiesMsgProc struct {
	es IEntities
}

func (this *EntitiesMsgProc) MsgProc_CreateEntityReqSrv(msg *protomsg.CreateEntityReqSrv) {
	_, err := this.es.CreateEntity(msg.EntityType, msg.EntityID, msg.DBID, false)

	msgRet := &protomsg.CreateEntityRetSrv{
		CreateEntityID: msg.EntityID,
		CallbackID:     msg.CallbackID,
		ResultMsg: &protomsg.CodeRet{
			Code:        0,
			CodeMessage: "",
		},
	}
	if err != nil {
		msgRet.ResultMsg.Code = int64(common.GetErrno(err))
		msgRet.ResultMsg.CodeMessage = err.Error()
	}

	if err := global.GetSrvInst().PostMsgToEntity(msg.SrcSrvID, msg.SrcSpaceID, msg.SrcEntityID, msgRet); err != nil {
		logger.Error(err)
	}
}

func (this *EntitiesMsgProc) MsgProc_CreateEntityRetSrv(msg *protomsg.CreateEntityRetSrv) {
	//其实不需要做什么
	logger.Debugf(logger.LogKey_Entity, "收到创建实体的回复,%v", msg)
}

func (this *EntitiesMsgProc) MsgProc_DestroyEntityReqSrv(msg *protomsg.DestroyEntityReqSrv) {
	//删成员
	err := this.es.DestroyEntity(msg.EntityID)
	msgRet := &protomsg.DestroyEntityRetSrv{
		DestroyEntityID: msg.EntityID,
		CallbackID:      msg.CallbackID,
		ResultMsg: &protomsg.CodeRet{
			Code:        0,
			CodeMessage: "",
		},
	}
	if err != nil {
		msgRet.ResultMsg.Code = int64(common.GetErrno(err))
		msgRet.ResultMsg.CodeMessage = err.Error()
	}
	if err := global.GetSrvInst().PostMsgToEntity(msg.SrcSrvID, msg.SrcSpaceID, msg.SrcEntityID, msgRet); err != nil {
		logger.Error(err)
	}
}

func (this *EntitiesMsgProc) MsgPorc_DestroyEntityRetSrv(msg *protomsg.DestroyEntityRetSrv) {
	//删成功后的回复
	emd := this.es.GetEntity(msg.DestroyEntityID)
	if emd == nil {
		return
	}
	if ereal, ok := emd.(IPost); ok {
		ereal.RefreshSrvIDS()
	}
	logger.Debugf(logger.LogKey_Entity, "收到删除实体的回复,%v", msg)
}

func (this *EntitiesMsgProc) Srv_DestroyEntityReqSrv(req *protomsg.RouteMsgSrvReq, msg *protomsg.DestroyEntityReqSrv) error {
	err := this.es.DestroyEntity(msg.EntityID)
	if err == nil {
		return common.Err_Success
	}
	return err
}

func (this *EntitiesMsgProc) Srv_CreateEntityReqSrv(req *protomsg.RouteMsgSrvReq, msg *protomsg.CreateEntityReqSrv) error {
	_, err := this.es.CreateEntity(msg.EntityType, msg.EntityID, msg.DBID, false)
	if err == nil {
		return common.Err_Success
	}
	return err
}
